from sqlmodel import select
from sqlalchemy.orm import joinedload
from app import  models,crud
from typing import Optional
from app.core.security import get_password_hash
from fastapi import status
from .base import BaseService
from app.utils import generate_verification_code,send_sms
from datetime import datetime,timedelta
class UserProfileService(BaseService):  
    async def create_profile(self, payload: models.UserProfileUpdateMe) -> models.UserPublicResponse:

        profile = await crud.UserProfile(self.db).find_by({"userId":self.current_user.id})
        
        if profile:
            return models.UserPublicResponse(
                code=status.HTTP_400_BAD_REQUEST,
                msg="用户prfile已经存在",
                data=None
            )        
        user_data = payload.model_dump(exclude_unset=True)            
        profile_create = models.UserProfile(userId=self.current_user.id,**user_data)
        self.db.add(profile_create)
        self.db.commit()
        self.db.refresh(profile_create)
        return models.UserPublicResponse(
                code=0,
                msg="创建成功",
                data=profile_create
            )
    
    async def update_me(
        self,  payload: models.UserProfileUpdateMe
    ) -> models.UserPublicResponse:
        return await self.update_user_by_id(self.current_user.id,payload)
    
    async def update_user_by_id(
        self,user_id:int,  payload: models.UserProfileUpdateMe
    ) -> models.UserPublicResponse:
        
        db_user = await crud.User(self.db).find(user_id)
        if not db_user:
            return models.UserPublicResponse(code=status.HTTP_404_NOT_FOUND,
                msg="The user with this id does not exist in the system",data=None)
            
        user_data = payload.model_dump(exclude_unset=True)
        # if "password" in user_data:
        #     password = user_data["password"]
        #     hashed_password = get_password_hash(password)
        #     extra_data["hashed_password"] = hashed_password

        db_user.sqlmodel_update(user_data)
        self.db.add(db_user)
        self.db.commit()
        self.db.refresh(db_user)
        return  models.UserPublicResponse(code=0,
                    msg="更新成功",data=db_user)    
        